package com.dong.binaryTree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author dcz
 * @classname CountNodes
 * @description 计算节点数
 * @date 2022/4/30 14:26
 */
public class CountNodes {
    //递归解法
    public int countNodes(TreeNode root) {
        if (root == null){
            return 0;
        }
        return countNodes(root.left)+countNodes(root.right)+1;
    }

    //迭代法
    public int countNodes2(TreeNode root) {
        if ( root == null){
            return 0;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int result = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size --> 0){
                TreeNode cur = queue.poll();
                result++;
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null){
                    queue.offer(cur.right);
                }
            }
        }
        return result;
    }
}
